package main.Baskets;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import main.BaseServlet;
import main.Basket;
import main.Item;
import main.PMF;

import DBClasses.ItemPair;

@SuppressWarnings("serial")
public class BuyFromBasket extends BaseServlet
{
	@SuppressWarnings({ "unchecked" })
	@Override
	protected void action(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException
	{
		Basket bskt = (Basket) req.getSession().getAttribute("basket");
		if (bskt != null && bskt.UserBasket.size() > 0)
		{
			PersistenceManager manager = PMF.get().getPersistenceManager();
			List<ItemPair> it_prs = (List<ItemPair>) manager.newQuery(
					"select from " + ItemPair.class.getName()).execute();
			for (int i = 0; i < bskt.UserBasket.size(); i++)
			{
				Item item1 = bskt.UserBasket.get(i);
				for (int j = i + 1; j < bskt.UserBasket.size(); j++)
				{
					Item item2 = bskt.UserBasket.get(j);
					ItemPair new_ip = null;
					if (it_prs != null && it_prs.size() > 0)
					{
						for (ItemPair itemPair : it_prs)
						{
							if ((itemPair.get1id() == item1.getGame().getId() && itemPair
									.get2id() == item2.getGame().getId())
									|| (itemPair.get1id() == item2.getGame()
											.getId() && itemPair.get2id() == item1
											.getGame().getId()))
								new_ip = itemPair;
						}
					}
					if (new_ip == null)
						new_ip = new ItemPair(item1.getGame().getId(), item2
								.getGame().getId());
					else
						new_ip.setCount(new_ip.getCount() + 1);
					manager.makePersistent(new_ip);
				}
			}
			manager.close();
			resp.getWriter().write("10.0");
		}
		else
			resp.getWriter().write("0.0");
	}
}
